package io.kiki.sba.registry.task;


import io.kiki.sba.registry.util.StringFormatter;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.util.concurrent.RejectedExecutionException;
import java.util.concurrent.RejectedExecutionHandler;
import java.util.concurrent.ThreadPoolExecutor;

public final class RejectedLogErrorHandler implements RejectedExecutionHandler {
    private final Logger logger = LoggerFactory.getLogger(RejectedLogErrorHandler.class);
    private final boolean throwException;

    public RejectedLogErrorHandler(boolean throwException) {

        this.throwException = throwException;
    }

    @Override
    public void rejectedExecution(Runnable r, ThreadPoolExecutor executor) {
        String msg = StringFormatter.format("Task {}: {} rejected from {}", r.getClass(), r, executor);
        logger.error(msg);
        if (throwException) {
            throw new RejectedExecutionException(msg);
        }
    }
}
